package 二分法;

/**
 * @author zhengTao
 * @version 1.0
 * @description:  x 的平方根，主要考虑防止越界情况
 * @date 2022/10/14 13:09
 */
public class Demo69 {
    public static void main(String[] args) {
        System.out.println(mySqrt(2147395599));

    }
    public static  int mySqrt(int x) {
          //防止除数是 0
          if(x<=1){
              return x;
          }
          int left= 0;
          int right=x;
          while (left<=right){
              //防止越界
              int mid=left+(right-left)/2;
              //防止 mid*mid 越界
              if(x/mid>mid){
                  left=mid+1;
              }else if(x/mid<mid){
                  right=mid-1;
              }else {
                  return mid;
              }
          }
          //不是正好是相等的情况，取极限情况  n=0;
        return right;

    }
}
